<?php

class ArticleController extends BackendController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array(),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Article();
        $model->setScenario('create');
        $articleCategory = new ArticleCategory;
        $criteria = new CDbCriteria();
        $criteria->select = '*';
        $criteria->order = 'sort';
        $data = $articleCategory->findAll($criteria);
        foreach($data as $value) {
            $menuData['items'][$value['id']] = $value;
            $menuData['parents'][$value['parents']][] = $value['id'];
        }

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Article']))
		{
            $p = new CHtmlPurifier();
			$model->attributes=$_POST['Article'];
            $image = CUploadedFile::getInstance($model, 'image');
            if(is_object($image)&&(get_class($image)==='CUploadedFile')) {
                $model->image = $image->name;
            }
            $model->category_id = Yii::app()->request->getParam('category_id');
            $model->user_id = Yii::app()->user->id;
            $model->short_content = Common::cut_string(strip_tags($p->purify($model->content)),500,1);
            $model->create_time = date('Y-m-d H:i:s');
            $model->update_time = date('Y-m-d H:i:s');
            $model->is_hot = $_POST['Article']['is_hot'];
            $model->status = 0;
            
            if($model->validate()) {
                if(is_object($image)&&(get_class($image)==='CUploadedFile')) {
                    $model->image = time().mt_rand(5, 99999999).'_'.$image->name;
                }
                else {
                    $model->image = 0;
                }
                if($model->save()) {
                    if(is_object($image)&&(get_class($image)==='CUploadedFile')) {
                        $imageUrl = Yii::app()->basePath.'/../data/article/'.$model->image;
                        $image->saveAs($imageUrl);
                        $imageObj = Yii::app()->image->load($imageUrl);
                        $imageObj->resize(300,300);
                        $imageObj->save();
                    }
                    $this->redirect(array('admin'));
    			}
            }
		}
        
		$this->render('create',array(
			'model'=>$model,
            'menuData'=>$menuData,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
        $model->setScenario('update');
        $menuData['currentParents'] = $model->category_id;
        $articleCategory = new ArticleCategory;
        $criteria = new CDbCriteria();
        $criteria->select = '*';
        $criteria->order = 'sort';
        $data = $articleCategory->findAll($criteria);
        foreach($data as $value) {
            $menuData['items'][$value['id']] = $value;
            $menuData['parents'][$value['parents']][] = $value['id'];
        }

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Article']))
		{
            $p = new CHtmlPurifier();
			$model->attributes=$_POST['Article'];
            $image = CUploadedFile::getInstance($model, 'image');
			$model->attributes=$_POST['Article'];
            $model->category_id = Yii::app()->request->getParam('category_id');
            $model->short_content = Common::cut_string(strip_tags($p->purify($model->content)),500,1);
            $model->update_time = date('Y-m-d H:i:s');
            $model->is_hot = $_POST['Article']['is_hot'];
            $model->status = $_POST['Article']['status'];
            
            if($model->validate()) {
                if(is_object($image)&&  get_class($image)=='CUploadedFile') {
                    if(is_file(Yii::app()->basePath.'/../data/article/'.$model->image)) {
                        unlink(Yii::app()->basePath.'/../data/article/'.$model->image);
                    }
                    $model->image = time().mt_rand(5, 99999999).'_'.$image->name;
                    if($model->save()) {
                        $imageUrl = Yii::app()->basePath.'/../data/article/'.$model->image;
                        $image->saveAs($imageUrl);
                        $imageTmp = Yii::app()->image->load($imageUrl);
                        $imageTmp->resize(300,300);
                        $imageTmp->save();
                        $this->redirect(array('admin'));
                    }
                }
                else {
                    if($model->save())
                        $this->redirect(array('admin'));
                }
            }
		}

		$this->render('update',array(
			'model'=>$model,
            'menuData'=>$menuData,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model = $this->loadModel($id);
        if(is_file(Yii::app()->basePath.'/../data/article/'.$model->avatar)) {
            unlink(Yii::app()->basePath.'/../data/article/'.$model->avatar);
        }
        $model->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Article');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Article('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Article']))
			$model->attributes=$_GET['Article'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
    
    /**
     * Change status field
     */
    public function actionPublish($id) {
        $id = (int) $id;
        $status = (int) Yii::app()->request->getParam('status');
        $model = $this->loadModel($id);
        if($status == 1)
            $model->status = 0;
        else
            $model->status = 1;
        $model->update('status');
        
        if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
    
    /**
     * Change is_hot field
     */
    public function actionHot($id) {
        $is_hot = Yii::app()->request->getParam('is_hot');
        $model = $this->loadModel($id);
        if($is_hot == 1)
            $model->is_hot = 0;
        else
            $model->is_hot = 1;
        $model->update('is_hot');
        
        if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
    
    public function actionAjaxdelete() {
        if(isset($_POST['chk'])) {
            foreach($_POST['chk'] as $id) {
                $model = $this->loadModel($id);
                if (is_file(Yii::app()->basePath.'/../data/article/'.$model->image)) {
                    unlink(Yii::app()->basePath.'/../data/article/'.$model->image);
                }
                $model->delete();
            }
        }
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Article the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Article::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Article $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='article-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
